package com.mango.ch06;

import java.io.IOException;
import java.net.URISyntaxException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import com.mango.HDFSTools.HDFSAPI;

/**
 * 使用mapreduce框架计算移动平均，本例使用的是队列的方法
 * 
 * @author Mango
 *
 */
public class AverageJob {
	static Path inputPath = new Path("/AverageJob/input");// input
	static Path outPath = new Path("/AverageJob/output"); // output

	@SuppressWarnings("deprecation")
	public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
		// TODO Auto-generated method stub
		// 创建输入文件夹
		try {
			HDFSAPI hdfs = new HDFSAPI();
			hdfs.createDirectory(inputPath);
			// 先删除已经有的输出文件夹
			hdfs.delDirectory(outPath);
			// hdfs.orpOver();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			System.out.println("----------文件操作失败");
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Configuration conf = new Configuration();
		conf.set("winSize", "2");
		Job job = new Job(conf);
		job.setJarByClass(AverageJob.class);
		job.setJobName("AverageJobe");

		job.setPartitionerClass(AveragePointer.class);
		job.setGroupingComparatorClass(NaturalKeyGroupComparator.class);
		job.setSortComparatorClass(ComposeKeyComparetor.class);

		job.setNumReduceTasks(5);

		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);

		job.setReducerClass(AverageReducer.class);
		job.setMapperClass(MovingAverageMapper.class);

		job.setMapOutputKeyClass(ComposeKey.class);
		job.setMapOutputValueClass(NaturalValue.class);

		FileOutputFormat.setOutputPath(job, outPath);
		FileInputFormat.setInputPaths(job, inputPath);
		boolean status = job.waitForCompletion(true);
		System.exit(status ? 0 : 1);
	}

}
